package com.trkj.share;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.trkj.base.BaseActivity;
import com.trkj.base.Constants;
import com.trkj.base.OnResponseResultListener;
import com.trkj.base.newwork.ProgressBarDataFromRemote;
import com.trkj.taoruiyun.R;

import java.text.MessageFormat;

/**
 * 文章详情
 * Created by LiZanhong on 2015/06/21.
 */
public class ArticleDetailActivity extends BaseActivity{
    public static final String ACTION = "com.trkj.share.ArticleDetailActivity";

    @ViewInject(R.id.article_title)
    private TextView articleTitle;

    @ViewInject(R.id.share_author)
    private TextView shareAuthor;

    @ViewInject(R.id.share_date)
    private TextView shareDate;

    @ViewInject(R.id.share_reason)
    private TextView shareReason;

    @ViewInject(R.id.full_title)
    private TextView fullTitle;

    @ViewInject(R.id.content)
    private WebView wvContent;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_share_detail);
        ViewUtils.inject(this); //注入组件

        Intent intent = getIntent();
        long articleId = intent.getLongExtra("articleId", 0);

        readArticleDetail(articleId);
    }

    /**
     * 获取文章详情
     * @param articleId
     */
    protected void readArticleDetail(long articleId){
        String url = MessageFormat.format(Constants.ApiUrl.SHARE_ARTICLE_DETAIL, articleId);

        ProgressBarDataFromRemote dataFromRemote = new ProgressBarDataFromRemote(this);
        dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
            @Override
            public void onResponseResult(String result) {
                fillData(result);
            }
        });

        dataFromRemote.execute(url);
    }

    protected void fillData(String result){
        JSONObject jsonObject = JSON.parseObject(result);
        boolean success = jsonObject.getBoolean("success");

        if(!success){
            toast("网络不畅通或者文章不存在");
        }else{
            JSONObject data = jsonObject.getJSONObject("data");
            articleTitle.setText(data.getString("title_"));
            String author = data.getString("author");
            if(!TextUtils.isEmpty(author)) {
                shareAuthor.setText("作者：" + author);
            }
            shareDate.setText("发表时间：" + data.getString("date_").substring(0, 11));
            String reason = data.getString("reason_");
            if(TextUtils.isEmpty(reason)){
                shareReason.setVisibility(View.GONE);
            }else{
                shareReason.setVisibility(View.VISIBLE);
                shareReason.setText("推荐理由：" + reason);
            }

            //代码分享要显示完成标题
            if(data.getIntValue("type_") == Constants.Share.SHARE_TYEP_CODE){
                fullTitle.setVisibility(View.VISIBLE);
                fullTitle.setText(Html.fromHtml("完整标题：<br>" + data.getString("title_")));
            }else{
                fullTitle.setVisibility(View.GONE);
                fullTitle.setText("");
            }

            fillWebView(data.getString("content"));
        }
    }


    protected void fillWebView(String content){
        WebSettings webSettings = wvContent.getSettings();
        webSettings.setJavaScriptEnabled(true); //可以执行脚本
        //webSettings.setDefaultTextEncodingName("UTF-8") ;
        //webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        //String domainHtml = Constants.ApiUrl.addDomainForImage(content);

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean b = sp.getBoolean("show_image", true);
        StringBuffer html = new StringBuffer();
        html.append("<html><body><div style='word-wrap: break-word;word-break: normal;word-break:break-all;'>");
        if(b) {
            html.append(Constants.ApiUrl.addDomainForImage(content));
        }else{
            html.append(Constants.ApiUrl.deleteAllImage(content));
        }
        html.append("</div>");
        html.append("<script type=\"text/javascript\"> \tvar imgs = document.getElementsByTagName(\"img\"); \tfor(var i = 0; i < imgs.length; i ++){ \t\timgs[i].style.width = \"100%\"; \t} </script>");
        html.append("</body></html>");

        wvContent.loadDataWithBaseURL(null, html.toString(), "text/html", "utf-8", null);
    }

    @Override
    protected String getCustomerTitle() {
        return "文章阅读";
    }
}
